/*
 * Copyright © 2018 www.noark.xyz All Rights Reserved.
 * 
 * 感谢您选择Noark框架，希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ！
 * 除非符合Noark许可协议，否则不得使用该文件，您可以下载许可协议文件：
 * 
 * 		http://www.noark.xyz/LICENSE
 *
 * 1.未经许可，任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
 * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
 * 3.无论你对源代码做出任何修改和改进，版权都归Noark研发团队所有，我们保留所有权利;
 * 4.凡侵犯Noark版权等知识产权的，必依法追究其法律责任，特此郑重法律声明！
 */
package com.company.slg.login;

import static xyz.noark.log.LogHelper.logger;

import com.company.slg.player.PlayerInfo;
import com.company.slg.player.PlayerInfoRepository;

import xyz.noark.core.annotation.Autowired;
import xyz.noark.core.annotation.Controller;
import xyz.noark.core.annotation.controller.EventListener;
import xyz.noark.core.annotation.controller.ExecThreadGroup;
import xyz.noark.core.annotation.controller.PacketMapping;
import xyz.noark.core.event.EventManager;
import xyz.noark.core.network.Session.State;
import xyz.noark.core.util.Md5Utils;

/**
 * 登录协议入口类.
 *
 * @author 小流氓(176543888@qq.com)
 */
@Controller(threadGroup = ExecThreadGroup.ModuleThreadGroup)
public class LoginController {

	@Autowired
	private EventManager eventManager;
	@Autowired
	private PlayerInfoRepository playerInfoRepository;

	@PacketMapping(opcode = 1001, state = State.CONNECTED)
	public void login(LoginRequest request) {
		// 从缓存中取，如果没有，会自动从Mysql中取...
		PlayerInfo player = playerInfoRepository.cacheGet(request.getUsername());
		if (player == null) {
			logger.info("账号不存在 username={}", request.getUsername());
		} else if (!Md5Utils.encrypt(request.getPassword()).equalsIgnoreCase(player.getPassword())) {
			logger.info("密码不正确 password={}", request.getPassword());
		} else {
			logger.info("登录成功 username={}, password={}", request.getUsername(), request.getPassword());
		}

		// 假装他登录成功了...
		eventManager.publish(new OnlineEvent(1234));
	}

	@EventListener(OnlineEvent.class)
	public void handleOnlineEvent(OnlineEvent event) {
		logger.info("{} 上线了....", event.getPlayerId());
	}
}